<template>
    <div class="row row-of-cards">
        <div class="col-md-6">
            <section
                class="card"
                role="region"
                aria-labelledby="hdr_export_media"
            >
                <div class="card-header text-bg-primary">
                    <h2
                        id="hdr_export_media"
                        class="card-title"
                    >
                        {{ $gettext('Export Media to CSV') }}
                    </h2>
                </div>

                <div class="card-body">
                    <p class="card-text">
                        {{
                            $gettext('Click the button below to generate a CSV file with all of this station\'s media. You can make any necessary changes, and then import the file using the file picker on the right.')
                        }}
                    </p>
                    <p class="card-text">
                        {{
                            $gettext('Note: If your media metadata has UTF-8 characters, you should use a spreadsheet editor that supports UTF-8 encoding, like OpenOffice.')
                        }}
                    </p>

                    <div class="block-buttons">
                        <a
                            class="btn btn-block btn-primary"
                            :href="apiUrl"
                        >
                            {{ $gettext('Export Media to CSV') }}
                        </a>
                    </div>
                </div>
            </section>
        </div>
        <div class="col-md-6">
            <section
                class="card"
                role="region"
            >
                <div class="card-header text-bg-primary">
                    <h2 class="card-title">
                        {{ $gettext('Import Changes from CSV') }}
                    </h2>
                </div>

                <div class="card-body">
                    <p class="card-text">
                        {{
                            $gettext('The format and headers of this CSV should match the format generated by the export function on this page.')
                        }}
                    </p>

                    <form
                        class="form"
                        @submit.prevent="doSubmit"
                    >
                        <form-group id="import_file">
                            <template #label>
                                {{ $gettext('Select CSV File') }}
                            </template>

                            <template #default="{id}">
                                <form-file
                                    :id="id"
                                    @uploaded="uploaded"
                                />
                            </template>
                        </form-group>

                        <div class="block-buttons mt-3">
                            <button
                                type="button"
                                class="btn btn-block btn-outline-primary me-2"
                                @click="doPreview"
                            >
                                {{ $gettext('Preview Changes') }}
                            </button>
                            <button
                                type="submit"
                                class="btn btn-block btn-primary"
                                :disabled="!previewCompleted"
                            >
                                {{ $gettext('Import Changes from CSV') }}
                            </button>
                        </div>
                    </form>
                </div>
            </section>
        </div>

        <modal
            id="preview_modal"
            ref="$previewModal"
            :title="$gettext('Preview Changes')"
            size="lg"
        >
            <p class="card-text">
                {{ previewResults.message }}
            </p>

            <div style="max-height: 400px; overflow-y: scroll;">
                <table class="table table-striped table-responsive">
                    <thead>
                        <tr>
                            <th class="p-2">
                                {{ $gettext('Media File') }}
                            </th>
                            <th class="p-2">
                                {{ $gettext('Proposed Changes') }}
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr
                            v-for="row in filteredPreviewResults"
                            :key="row.id"
                        >
                            <td
                                class="p-2"
                                style="overflow-x: auto;"
                            >
                                <b>{{ row.title }}</b><br>
                                {{ row.artist }}
                            </td>
                            <td
                                class="p-2"
                                style="overflow-x: auto;"
                            >
                                <template v-if="row.error">
                                    <div class="text-danger">
                                        <i class="fas fa-exclamation-triangle"></i>
                                        {{ row.error }}
                                    </div>
                                </template>
                                <template v-else-if="row.has_changes">
                                    <div
                                        v-if="row.changes.metadata"
                                        class="mb-2"
                                    >
                                        <strong>{{ $gettext('Metadata:') }}</strong>
                                        <ul class="mb-0">
                                            <li
                                                v-for="change in row.changes.metadata"
                                                :key="change.field"
                                            >
                                                <strong>{{ change.field }}: </strong>
                                                <span class="text-muted">{{ change.current || '(empty)' }}</span>
                                                →
                                                <span class="text-success">{{ change.new || '(empty)' }}</span>
                                            </li>
                                        </ul>
                                    </div>
                                    <div
                                        v-if="row.changes.extra_metadata"
                                        class="mb-2"
                                    >
                                        <strong>{{ $gettext('Extra Metadata:') }}</strong>
                                        <ul class="mb-0">
                                            <li
                                                v-for="change in row.changes.extra_metadata"
                                                :key="change.field"
                                            >
                                                <strong>{{ change.field }}: </strong>
                                                <span class="text-muted">{{ change.current || '(empty)' }}</span>
                                                →
                                                <span class="text-success">{{ change.new || '(empty)' }}</span>
                                            </li>
                                        </ul>
                                    </div>
                                    <div
                                        v-if="row.changes.playlists"
                                        class="mb-2"
                                    >
                                        <strong>{{ $gettext('Playlists:') }}</strong>
                                        <ul class="mb-0">
                                            <li
                                                v-if="row.changes.playlists.added && row.changes.playlists.added.length > 0"
                                            >
                                                <span class="text-success">
                                                    <i class="fas fa-plus"></i>
                                                    {{ $gettext('Add to:') }} {{ row.changes.playlists.added.join(', ') }}
                                                </span>
                                            </li>
                                            <li
                                                v-if="row.changes.playlists.removed && row.changes.playlists.removed.length > 0"
                                            >
                                                <span class="text-danger">
                                                    <i class="fas fa-minus"></i>
                                                    {{ $gettext('Remove from:') }} {{ row.changes.playlists.removed.join(', ') }}
                                                </span>
                                            </li>
                                        </ul>
                                    </div>
                                    <div
                                        v-if="row.changes.custom_fields"
                                        class="mb-2"
                                    >
                                        <strong>{{ $gettext('Custom Fields:') }}</strong>
                                        <ul class="mb-0">
                                            <li
                                                v-for="change in row.changes.custom_fields"
                                                :key="change.field"
                                            >
                                                <strong>{{ change.field }}: </strong>
                                                <span class="text-muted">{{ change.current || '(empty)' }}</span>
                                                →
                                                <span class="text-success">{{ change.new || '(empty)' }}</span>
                                            </li>
                                        </ul>
                                    </div>
                                </template>
                                <template v-else>
                                    <div class="text-muted">
                                        {{ $gettext('No changes') }}
                                    </div>
                                </template>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <template #modal-footer>
                <button
                    class="btn btn-secondary"
                    type="button"
                    @click="hidePreview"
                >
                    {{ $gettext('Cancel') }}
                </button>
                <button
                    class="btn btn-success"
                    type="button"
                    @click="proceedWithImport"
                    :disabled="!previewResults || previewResults.total_changes === 0"
                >
                    {{ $gettext('Proceed with Import') }}
                </button>
            </template>
        </modal>

        <modal
            id="import_modal"
            ref="$modal"
            :title="$gettext('Import Results')"
        >
            <p class="card-text">
                {{ importResults.message }}
            </p>

            <div style="max-height: 300px; overflow-y: scroll;">
                <table class="table table-striped table-responsive">
                    <thead>
                        <tr>
                            <th class="p-2">
                                {{ $gettext('Media File') }}
                            </th>
                            <th class="p-2">
                                {{ $gettext('Import Results') }}
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr
                            v-for="row in importResults.import_results"
                            :key="row.id"
                        >
                            <td
                                class="p-2"
                                style="overflow-x: auto;"
                            >
                                <b>{{ row.title }}</b><br>
                                {{ row.artist }}
                            </td>
                            <td
                                class="p-2"
                                style="overflow-x: auto;"
                            >
                                <template v-if="row.success">
                                    <div class="text-success">
                                        {{ $gettext('Updated successfully.') }}
                                    </div>
                                </template>
                                <template v-else>
                                    <div class="text-danger">
                                        {{ $gettext('Unable to update.') }}
                                    </div>
                                    <div v-if="row.error">
                                        {{ row.error }}
                                    </div>
                                </template>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <template #modal-footer>
                <button
                    class="btn btn-secondary"
                    type="button"
                    @click="hide"
                >
                    {{ $gettext('Close') }}
                </button>
            </template>
        </modal>
    </div>
</template>

<script setup lang="ts">
import {computed, ref, useTemplateRef} from "vue";
import {useNotify} from "~/components/Common/Toasts/useNotify.ts";
import {getErrorAsString, useAxios} from "~/vendor/axios";
import Modal from "~/components/Common/Modal.vue";
import FormGroup from "~/components/Form/FormGroup.vue";
import FormFile from "~/components/Form/FormFile.vue";
import {useHasModal} from "~/functions/useHasModal.ts";
import {ApiStatus} from "~/entities/ApiInterfaces.ts";
import {useApiRouter} from "~/functions/useApiRouter.ts";

const {getStationApiUrl} = useApiRouter();
const apiUrl = getStationApiUrl('/files/bulk');
const previewApiUrl = getStationApiUrl('/files/bulk/preview');

const importFile = ref<File | null>(null);
const importResults = ref<any>(null);
const previewResults = ref<any>(null);
const previewCompleted = ref<boolean>(false);

const {notifySuccess, notifyError} = useNotify();
const {axios} = useAxios();

const $modal = useTemplateRef('$modal');
const {show, hide} = useHasModal($modal);

const $previewModal = useTemplateRef('$previewModal');
const {show: showPreview, hide: hidePreview} = useHasModal($previewModal);

const filteredPreviewResults = computed(() => {
    if (!previewResults.value?.previewResults) return [];
    return previewResults.value.previewResults.filter((row: any) =>
        row.has_changes || row.error
    );
});

const uploaded = (file: File) => {
    importFile.value = file;
    previewCompleted.value = false;
    previewResults.value = null;
};

const doPreview = async () => {
    if (!importFile.value) {
        notifyError('Please select a CSV file first.');
        return;
    }

    const formData = new FormData();
    formData.append('import_file', importFile.value);

    try {
        const {data} = await axios.post<ApiStatus>(previewApiUrl.value, formData);

        if (data.success) {
            previewResults.value = data;
            previewCompleted.value = true;
            showPreview();
        } else {
            notifyError(data.message || 'Preview failed');
        }
    } catch (e) {
        const errorMsg = getErrorAsString(e);
        notifyError(`Preview failed: ${errorMsg}`);
    }
};

const proceedWithImport = () => {
    hidePreview();
    void doSubmit();
};

const doSubmit = async () => {
    if (!previewCompleted.value) {
        notifyError('Please preview the changes first.');
        return;
    }
    if (!importFile.value) {
        notifyError('No file provided.');
        return;
    }

    const formData = new FormData();
    formData.append('import_file', importFile.value);

    const {data} = await axios.post<ApiStatus>(apiUrl.value, formData);

    importFile.value = null;
    previewCompleted.value = false;
    previewResults.value = null;

    if (data.success) {
        importResults.value = data;
        notifySuccess(data.message);
        show();
    } else {
        notifyError(data.message);
        hide();
    }
};
</script>
